package org.aokey.springdemo2;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

@RestController
public class CookieController {
    @RequestMapping("/Q1")
    public String Q1(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies=request.getCookies();
        StringBuilder builder=new StringBuilder();
        if(cookies!=null){
            for(Cookie ck:cookies){
                builder.append(ck.getName()+":"+ck.getValue());
            }
        }
        return "Cookie信息："+builder;
    }
    @RequestMapping("/Q2")
    public String Q2(@CookieValue("Name") String name){
        return "Name:"+name;
    }
    @RequestMapping("/Q3")
    public String Q3(HttpServletRequest request){
        HttpSession session=request.getSession();
        if(session!=null){
            session.setAttribute("name","Aokey");
        }
        return "Session储存成功";
    }
    @RequestMapping("/Q4")
    public String Q4(HttpServletRequest request){
        HttpSession session=request.getSession(false);
        String name=null;
        if(session!=null&&session.getAttribute("name")!=null){
            name=session.getAttribute("name").toString();
        }
        return "获取到："+name;
    }
    @RequestMapping("/Q5")
    public String Q5(@SessionAttribute(value = "name",required = false) String name){
        return "Name:"+name;
    }
    @RequestMapping("/Q6")
    public String Q6(HttpSession session){
        String name=(String)session.getAttribute("name");
        return "Name:"+name;
    }
    @RequestMapping("/Header")
    public String Header(HttpServletRequest request,HttpServletResponse response){
        String userAgent=request.getHeader("User-Agent");
        return "User-Agent:"+userAgent;
    }
    @RequestMapping("/Header2")
    public String Header2(@RequestHeader("User-Agent") String userAgent){
        return "User-Agent:"+userAgent;
    }
}
